package com.daiziru.wuyanmall.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 作者：無言
 * 时间：2022/3/22 20:14
 * 描述：永无BUG
 */

/**
 * WebSocket服务器
 */
@Component //交给spring管理
@ServerEndpoint("/webSocket/{oid}") //请求路径oid是订单id
public class WebSocketServer {


    private static ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();//建立一个容器，当生成订单时，通过
    //websocket生成的对象存到这里面，当页面跳转或者订单完成的时候，移除当前的连接对象
    /**前端发送请求建⽴websocket连接，就会执⾏@OnOpen⽅法**/
    @OnOpen
    public void open(@PathParam("oid") String orderId, Session session){
        System.out.println("和订单建立连接------orderId:" + orderId);
        sessionMap.put(orderId, session);
    }

    /**前端关闭⻚⾯或者主动关闭websocket连接，都会执⾏close**/
    @OnClose
    public void close(@PathParam("oid") String orderId){
        sessionMap.remove(orderId);
    }

    public static void sendMsg(String orderId, String msg) {
        try{
            Session session = sessionMap.get(orderId);
            session.getBasicRemote().sendText(msg);//向前端发送消息
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
